// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.server.model.validators;

import java.util.Calendar;
import java.util.GregorianCalendar;
import net.taviscaron.drivenotes.shared.exceptions.InvalidEntityException;
import net.taviscaron.drivenotes.shared.model.entity.Car;
import static net.taviscaron.drivenotes.server.util.ExceptionUtils.invalidEntityException;

/**
 * Car validator
 * @author Andrei Senchuk
 */
public class CarValidator implements Validator<Car> {
    private static final int BRAND_MAX_SIZE = 45;
    private static final int MODEL_MAX_SIZE = 45;

    public enum Error {
        BRAND_IS_EMPTY, MODEL_IS_EMPTY,
        INVALID_ENGINE_VOLUME, INVALID_ODOMETR_VALUE,
        BRAND_IS_TOO_LONG, MODEL_IS_TOO_LONG
    }

    public void validate(Car car) throws InvalidEntityException {
        if(car.getBrand() == null || car.getBrand().trim().isEmpty()) {
            throw invalidEntityException(Error.BRAND_IS_EMPTY);
        }

        if(car.getBrand().length() > BRAND_MAX_SIZE) {
            throw invalidEntityException(Error.BRAND_IS_TOO_LONG);
        }

        if(car.getModel() == null || car.getModel().trim().isEmpty()) {
            throw invalidEntityException(Error.MODEL_IS_EMPTY);
        }

        if(car.getModel().length() > MODEL_MAX_SIZE) {
            throw invalidEntityException(Error.MODEL_IS_TOO_LONG);
        }

        if(car.getYear() != null &&
                (car.getYear() <= 0 || car.getYear() > GregorianCalendar.getInstance().get(Calendar.YEAR))) {
            throw invalidEntityException(Error.MODEL_IS_EMPTY);
        }

        if(car.getEngineVolume() != null && car.getEngineVolume() <= 0) {
            throw invalidEntityException(Error.INVALID_ENGINE_VOLUME);
        }

        if(car.getOdometrValue() != null && car.getOdometrValue() < 0) {
            throw invalidEntityException(Error.INVALID_ODOMETR_VALUE);
        }
    }
}
